package com.pg.agent.engine.service.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pg.agent.engine.client.message.InPutMessage;
import com.pg.agent.engine.client.message.OutPutMessage;
import com.pg.agent.engine.client.vo.SOPResultVO;
import com.pg.base.enums.ResultEnum;
import com.pg.base.exception.BizException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Slf4j
@Data
public class SSEListener extends EventSourceListener {

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    private JSONObject param;

    private String messageId;

    private HttpServletResponse rp;

    private OutPutMessage outMessage;

    private  InPutMessage message;

    private boolean last;

    private StringBuffer output = new StringBuffer();

    public SSEListener(JSONObject param, InPutMessage message, HttpServletResponse response, String messageId, OutPutMessage outMessage, boolean last) {
        this.param = param;
        this.rp = response;
        this.message = message;
        this.messageId = messageId;
        this.outMessage = outMessage;
        this.last = last;
    }

    /**
     * {@inheritDoc}
     * 建立sse连接
     */
    @Override
    public void onOpen(final EventSource eventSource, final Response response) {
        if (rp != null) {
            rp.setContentType("text/event-stream");
            rp.setCharacterEncoding("UTF-8");
            rp.setStatus(200);
            log.info("建立sse连接..." + JSON.toJSONString(param));

            outMessage.setTimeLong(System.currentTimeMillis() - outMessage.getCallStartTime().getTime());

            SOPResultVO vo = SOPResultVO.instance("", false, messageId, outMessage);
            if (outMessage.isFirst()){
                outMessage.setFirst(false);
                vo.setFirst(1);
            }
            try {
                rp.getWriter().write("data:" + JSONObject.toJSONString(vo) + "\n\n");
                rp.getWriter().flush();
            } catch (IOException e) {
                log.error("消息错误[" + JSON.toJSONString(param) + "]", e);
                countDownLatch.countDown();
            }

        } else {
            log.info("客户端非sse推送" + JSON.toJSONString(param));
        }
    }

    /**
     * 事件
     *
     * @param eventSource
     * @param id
     * @param type
     * @param data
     */
    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {
        Map<String, AtomicBoolean> atomicIntegerMap = SessionConnectManager.getInstance().getStoryMap();
        AtomicBoolean atomicBoolean = atomicIntegerMap.get(message.getSessionId());
        if (atomicBoolean != null && !atomicBoolean.get()){
            SessionConnectManager.getInstance().addStopSessionId(message.getSessionId());
            log.info("流程中断");
            countDownLatch.countDown();
        }
        try {
            int status = 0;

            boolean finish = false;
            String content = null;
            try {
                JSONObject result = JSONObject.parseObject(data);
                status = result.getInteger("status");
                content = result.getString("content");
                if (StringUtils.isNotEmpty(content)) {
                    output.append(content);
                }
                if (status == 2) {
                    finish = last;
                }
            } catch (Exception e) {
                content = data;
            }

            if (rp != null) {
                if ("\n".equals(data)) {
                    rp.getWriter().write("event:" + type + "\n");
                    rp.getWriter().write("id:" + id + "\n");
                    rp.getWriter().write("data:\n\n");
                    rp.getWriter().flush();
                } else {
                    SOPResultVO vo = SOPResultVO.instance(content, finish, messageId, null);

                    rp.getWriter().write("data:" + JSONObject.toJSONString(vo) + "\n\n");
                    rp.getWriter().flush();
                }
            }
        } catch (Exception e) {
            log.info("data:{}", data);
            log.error("消息错误[" + JSON.toJSONString(param) + "]", e);
            countDownLatch.countDown();
            throw new BizException(ResultEnum.ERROR, e);
        }

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onClosed(final EventSource eventSource) {
        //     log.info("sse连接关闭:{}", param.getMessageId());
        log.info("结果输出:{}" + output.toString());
        countDownLatch.countDown();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onFailure(final EventSource eventSource, final Throwable t, final Response response) {
        //    log.error("使用事件源时出现异常... [响应：{}]...", param.getMessageId());
        countDownLatch.countDown();
    }

    public CountDownLatch getCountDownLatch() {
        return this.countDownLatch;
    }
}

